<template>
  <el-dialog v-model="dialogInfo.visible" :title="dialogInfo.title" :width="dialogInfo.width" align-center>
    <el-form ref="formRef" label-position="left" :model="formModel" :rules="formRules" label-width="120px">
      <el-form-item label="学期名称" prop="title">
        <el-input class="w100" v-model.trim="formModel.title" autocomplete="off" placeholder="请输入学期名称"></el-input>
      </el-form-item>
      <el-form-item label="开始时间" prop="startDate">
        <el-date-picker class="w100" v-model="formModel.startDate" type="date" placeholder="开始时间" @change="handelDateFrom" clearable></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endDate">
        <el-date-picker class="w100" v-model="formModel.endDate" type="date" placeholder="结束时间" @change="handelDateTo" :disabled="!formModel.startDate" :disabled-date="pickerOptions" @focus="changeEndTime(formModel.startDate)" clearable></el-date-picker>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="info" plain @click="onCancel()">取消</el-button>
        <el-button type="primary" @click="onSubmit()">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>
  
  <script setup>
/**
*/
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import { getNewObj } from '@/utils/EsCommon';
import { resetForm } from '@/utils/EsDate.js';

// ======================================================
//                      变量声明
// ======================================================
const value1 = ref('')

// emit
const emit = defineEmits(['success']);
// 表单数据
const formAttrs = {

  id: "",
  startDate: "",
  endDate: "",
  sort: "",
  title: "",
};
const formModel = ref(Object.assign({}, formAttrs));
// 弹窗信息
const dialogInfo = ref({
  visible: false,
  title: '',
  width: '800px',
})
// 表单组件的引用实例
const formRef = ref(null);
// 加载状态

// 选项数据
// 分类ID树形选项数据
const optionsOfCategoryId = ref([]);
// 是否热门选项数据
const optionsOfIsHot = ref({});
// 是否推荐选项数据
const optionsOfIsRecommend = ref({});
// 状态选项数据
const optionsOfStatus = ref({});
const beginDateVal = ref("");
// 开始时间变化时判断是否大于结束时间
const startChange = item => {
  beginDateVal.value = new Date(formModel.value.startDate).getTime();
 
  let endVal =
    formModel.value.endDate == "" ? 0 : new Date(formModel.value.endDate).getTime();
  if (formModel.value.endDate == "") {
    return false;
  } else if (beginDateVal.value > endVal) {
    formModel.value.endDate = "";
  }
};
 
//结束时间input框获取焦点的时候，计算禁用范围
const changeEndTime = val => {
  pickerOptions();
};
const pickerOptions = time => {
  return time?.getTime() <= beginDateVal.value - 8.64e7;
};

// 自定义验证规则(校验开始日期)
const validationDateFrom = (rule, value, callback) => {
  // 比较时间戳(进行运算的时候会自动转换成时间戳进行运算，不运算的时候，显示中国标准时间格式)
  if (
    new Date(formModel.value.endDate) - new Date(value) <= 0 &&
    formModel.value.endDate &&
    value
  ) {
    return callback(new Error('开始时间不能大于结束时间'))
  }
  callback()
}
// 自定义验证规则(校验截止日期)
const validationDateTo = (rule, value, callback) => {
  // 比较时间戳(进行运算的时候会自动转换成时间戳进行运算，不运算的时候，显示中国标准时间格式)
  if (
    new Date(value) - new Date(formModel.value.startDate) <= 0 &&
    formModel.value.endDate &&
    value
  ) {
    return callback(new Error('结束时间不能小于开始时间'))
  } callback()
}



// 表单校验规则
const formRules = ref({
  title: [{ required: true, trigger: "blur", message: "请输入学期名称" }],
  startDate: [
    { required: true, trigger: "blur", message: "请选择开始时间" },
    { validator: validationDateFrom }
  ],
  endDate: [
    { required: true, trigger: "blur", message: "请选择结束时间" },
    { validator: validationDateTo }
  ],
})

// 当开始时间变化时,需要重新校验
const handelDateFrom = (value) => {
  startChange()
  if (new Date(formModel.value.endDate) - new Date(value) > 0 && formModel.value.endDate &&
    value
  ) {
    // 重新校验
    formRef.value.validate()
  }
}
const handelDateTo = (value) => {
  if (
    new Date(value) - new Date(formModel.value.startDate) > 0 &&
    formModel.value.startDate &&
    value
  ) {
    formRef.value.validate()
  }
}
// ======================================================
//                      点击操作
// ======================================================

// 点击提交按钮
const onSubmit = () => {
  formRef.value.validate((valid, fields) => {
    if (!valid) {
      console.log('表单校验失败：', fields);
      return;
    }


    var param = {
      ...formModel.value,
      startDate: resetForm('YYYY-mm-dd', formModel.value.startDate) || '',
      endDate: resetForm('YYYY-mm-dd', formModel.value.endDate) || ''
    };



    EsAjax.post(ApiUrls.semesterConfigEdit, param).then(res => {
      if (res.data.code != 200) {
        ElMessage.warning(res.data.data + res.data.msg);
        return;
      }
      dialogInfo.value.visible = false;
      ElMessage.success('操作成功');
      emit('success');
    }).catch(err => {
      ElMessage.error('网络错误：' + err.message);
    })
  })
}




// 点击取消按钮
const onCancel = () => {
  formModel.value = Object.assign({}, formAttrs);
  formRef.value.resetFields();
  dialogInfo.value.visible = false;
}

// ======================================================
//                      处理事件
// ======================================================


// 加载数据
const show = (id, title, item = null, width = '600px') => {
  dialogInfo.value.title = title;
  dialogInfo.value.width = width;
  dialogInfo.value.visible = true;
  formModel.value = Object.assign({}, formAttrs);

  if (item) {
    formModel.value = Object.assign({ ...formAttrs }, getNewObj(item));
  }

}

defineExpose({
  show
})
  </script>